<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>家谱详情</span>
        <el-button type="primary" @click="openPersonDialog()">添加新成员</el-button>
      </div>
    </template>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="家谱图表" name="chart">
        <FamilyTreeChart
          v-if="treeId"
          :key="chartKey"
          :tree-id="treeId"
          @node-click="showPersonDetails"
          ref="chartComponentRef"
        />
      </el-tab-pane>
      <el-tab-pane label="成员列表" name="list">
        <el-table :data="persons" v-loading="loading" style="width: 100%">
          <el-table-column prop="personId" label="ID" width="80" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              {{ scope.row.gender === 'M' ? '男' : (scope.row.gender === 'F' ? '女' : '其他') }}
            </template>
          </el-table-column>
          <el-table-column prop="birthDate" label="出生日期" />
          <el-table-column prop="deathDate" label="逝世日期" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
                <el-button size="small" @click="showPersonDetails(scope.row.personId)">详情</el-button>
                <el-button size="small" type="primary" @click="openPersonDialog(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </el-card>

  <PersonFormDialog v-if="treeId" v-model:visible="personFormVisible" :family-id="treeId" :person-data="selectedPersonForEdit" @success="refreshAllData"/>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getPersonsByFamilyTreeIdApi } from '@/api/family';
import type { Person, PersonFormData } from '@/types/api';
import FamilyTreeChart from '@/components/FamilyTreeChart.vue';
import PersonFormDialog from '@/components/PersonFormDialog.vue';

const props = defineProps<{ id: string }>();
const router = useRouter();
const treeId = Number(props.id);

const loading = ref(false);
const activeTab = ref('chart');
const persons = ref<Person[]>([]);
const chartKey = ref(0);
const chartComponentRef = ref<{ refreshChart: () => void }>();

const personFormVisible = ref(false);
const selectedPersonForEdit = ref<PersonFormData | null>(null);

const fetchPersons = async () => {
  if (!treeId) return;
  loading.value = true;
  try {
    persons.value = await getPersonsByFamilyTreeIdApi(treeId);
  } finally {
    loading.value = false;
  }
};

const refreshAllData = () => {
  fetchPersons();
  if (chartComponentRef.value) {
    chartComponentRef.value.refreshChart();
  }
};

const showPersonDetails = (personId: number) => {
  router.push({ name: 'PersonDetail', params: { id: personId } });
};

// 处理类型不匹配的问题
const openPersonDialog = (person?: Person) => {
  if (person) {
    // 手动创建一个新的、符合 PersonFormData 类型的对象
    // 只包含表单需要的字段，丢弃 isDeleted, familyName 等额外字段
    selectedPersonForEdit.value = {
      personId: person.personId,
      familyId: person.familyId,
      name: person.name,
      gender: person.gender || 'M', // 提供一个默认值，防止 undefined
      birthDate: person.birthDate,
      deathDate: person.deathDate,
    };
  } else {
    // 如果是新增，则清空
    selectedPersonForEdit.value = null;
  }
  personFormVisible.value = true;
};

onMounted(fetchPersons);
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
